#pragma once
#include "tcp_socket.hpp"
#include <functional>

typedef std::function<void (const std::string &, std::string *)> Handler;

class Tcp_server
{
public:
    Tcp_server() 
    {
    }
    bool Start(Handler handler)
    {
        if (listen_sock_.Socket() == 0)
        {
            perror("listen_sock_create_error");
            return 0;
        }
        if (listen_sock_.Bind() == 0)
        {
            perror("listen_sock_bind_error");
            return 0;
        }
        if(listen_sock_.Listen(5)==0)
        {
            perror("listen_sock_listen_error");
            return 0;
        }
        //进入时间循环
        while (1)
        {
            TcpSocket new_socket;
            std::string ip;
            uint16_t port;
            if(!listen_sock_.Accept(&new_socket,&ip,&port))
            {
                continue;
            }
            printf("we connected ip[%s] port[%d]!!successful!!\n",ip.c_str(),port);
            while(1)//循环读写
            {
                std::string req;
                bool ret=new_socket.Recv(&req);
                if(ret<0)
                {
                    printf("so ip[%s] port[%d] disconnected!!!!\n",ip.c_str(),port);
                    new_socket.Close();
                    break;
                }
                std::string resp;
                handler(req,&resp);
                new_socket.Send(resp);
                printf("we send client :%s \n",resp.c_str());
            }
            return true;
        }
        
    }

private:
    TcpSocket listen_sock_;
};